<?php

namespace Constructor;

abstract class AbstractInstances implements IContainer
{
    protected $factory;
    protected $containerInstances;
    
    public function __construct( IFactory $factory, Container $container ) 
    { 
        $this->factory = $factory; 
        $this->containerInstances = $container;
    }
    
    public function get( $identifier = NULL )
    {
        if( ! $this->containerInstances->has( $identifier ) )
        {
            $this->containerInstances->set( $identifier, $this->factory->create( $identifier ) );
        }
        
        return $this->containerInstances->get( $identifier );
    }
    
    public function reset() { $this->containerInstances->reset(); }
    public function count() { return $this->containerInstances->count(); }
    public function getIdentifiers() { return $this->containerInstances->getIdentifiers(); }
    
    public function set( $instance, $identifier = NULL ) 
    { 
        if( ! is_string( $identifier ) OR is_null( $identifier ) OR empty( $identifier ) ) 
        {
            $identifier = get_class( $instance );
        }
        
        $this->containerInstances->set( $identifier, $instance ); 
        return TRUE;
    }
    
    public function has( $identifier ) 
    { 
        return $this->containerInstances->has( $identifier ); 
    }
    
    public function create( $identifier = NULL, array $aliases = array() ) 
    { 
        $this->containerInstances->set( $identifier, $instance = $this->factory->create( $identifier, $aliases ) );
        return $instance; 
    }
}

